<?php
/**
 * YOption.php
 *
 * @author Hua Yang <htmlcook@gmail.com>
 * @since 2.0
 */

/**
 * Class YOption
 */
class YOption extends CApplicationComponent
{
	/**
	 * @var string
	 */
	public $table = '{{option}}';

	/**
	 * @var array
	 */
	protected $options;

	/**
	 * @var CDbConnection
	 */
	protected $db;

	public function init()
	{
		parent::init();

		if (!isset($this->db)) {
			$this->db = Yii::app()->getDb();
		}

		if (!isset($this->options)) {
			if (($options = $this->getCache()->get('setting_options')) === false) {
				$options = array();
				$rows = $this->db->createCommand()
					->select('*')
					->from($this->table)
					->queryAll();
				foreach ($rows as $row) {
					$options[$row['name']] = unserialize($row['value']);
				}
				$this->getCache()->set('setting_options', $options);
			}
			foreach (Yii::app()->getParams() as $name => $value) {
				$this->options[$name] = $value;
			}
			$this->options = array_merge($this->options, $options);
		}
	}

	/**
	 * 获取缓存
	 *
	 * @return CCache
	 */
	protected function getCache()
	{
		if (Yii::app()->hasComponent('cache')) {
			return Yii::app()->getCache();
		} else {
			return Yii::createComponent(array(
				'class' => 'CDummyCache'
			));
		}
	}

	/**
	 * 获取一个选项
	 *
	 * @param string $name
	 * @param mixed $default
	 * @return mixed
	 */
	public function get($name, $default = null)
	{
		return isset($this->options[$name]) ? $this->options[$name] : $default;
	}

	/**
	 * 设置一个选项
	 *
	 * @param string $name
	 * @param mixed $value
	 * @param bool $clearCache
	 */
	public function set($name, $value, $clearCache = true)
	{
		if (array_key_exists($name, $this->options) && $this->options[$name] === $value) {
			return;
		}

		$exists = (bool)$this->db->createCommand()
			->from($this->table)
			->where('name=:name', array(':name' => $name))
			->queryRow();
		if ($exists) {
			$this->db->createCommand()->update($this->table, array(
				'value' => serialize($value)
			), 'name=:name', array(':name' => $name));
		} else {
			$this->db->createCommand()->insert($this->table, array(
				'name' => $name,
				'value' => serialize($value)
			));
		}

		if ($clearCache) {
			$this->clearCache();
		}
		$this->options[$name] = $value;
	}

	/**
	 * 删除一个设置
	 *
	 * @param string $name
	 */
	public function del($name)
	{
		$this->db->createCommand()->delete($this->table, 'name=:name', array(':name' => $name));
		$this->clearCache();
		unset($this->options[$name]);
	}

	/**
	 * 更新设置缓存
	 */
	public function clearCache()
	{
		$this->getCache()->delete('setting_options');
	}

	/**
	 * 所有选项
	 *
	 * @return array
	 */
	public function getOptions()
	{
		return $this->options;
	}
}